<?php
/**
 * Geneone: Content Management Framework
 * Forum Object View
 *
 * http://geneone.neondragon.net/
 *
 * @package Geneone
 * @author Khlo
 * @version 1.0
 * @copyright 2004-2006 Geneone Development Team
 */
 
require_once ("Gene/Object/View.php");

class Gene_Object_View_Forum extends Gene_Object_View {
	/**
	 * Class Constructor
	 *
	 * @var object $model Gene_Object_Model object
	 */
	function Gene_Object_View_Forum(&$model) {
		$this->model =& $model;
	}
	
	/**
	 * Show this object. Returns HTML output code for object.
	 *
	 * @var array $actions Additional Arguments
	 *
	 * @return string HTML output for object.
	 */
	function view($actions=array()) {
		$tpl =& Gene::getTemplate();
		$db =& Gene::getDatabase();
		$user =& Gene::getUser();
		
		/* General Object Information */
		$info = $this->model->get();
		
		$tpl->assign ("pagetitle", $info['title']);
		$tpl->assign ("object", $info);
		
		/* Taxonomy */
		$worldset =& $this->model->getTaxonomySet();
		$userset =& $this->model->getUserTaxonomySet();
		
		/* Parents */
		$parents = $this->model->getParents();
		$tpl->assign ("parents", $parents);
		
		/* Standalone */
		$standalone = $this->model->isStandAlone();
		$tpl->assign ("standalone", $standalone);
		
		/* Childs */
		$forums = $this->model->getChilds(array(
			"where" => "type='forum'",
			"tables" => array(Gene::tableName("discussions"), Gene::tableName("forums")),
			"order" => "priority DESC, o.t_create ASC"
		));
		
		$this->model->enablePaging(25);
		$tpl->assign ("perpage", 25);
		
		if (isset($actions[2]) && isset($actions[3]) && $actions[2] == "tag") {
			$tag = str_replace("_", " ", $actions[3]);
			$showingusertag = false;
			
			if ($actions[3]{0} == "~") {
				$taguser =& Gene_User::fromPublicName(substr($actions[3], 1));
				if (isset($actions[4])) {
					$tag = str_replace("_", " ", $actions[4]);
				}
				
				if ($taguser) {
					$showingusertag = true;
					$tpl->assign ("usertag", $taguser->getInfo());
				}
			}
				
			if ($showingusertag) {	
				$usertagset =& $this->model->getUserTaxonomySet($taguser->getUserId());
				$numobjects = $usertagset->getNumObjectsWithLabel($tag);
			} else {
				$numobjects = $worldset->getNumObjectsWithLabel($tag);
			}
			
			$tpl->assign ("tagobjectcount", $numobjects);
			$numpages = ceil($numobjects / 25);
			$page = Gene_Request::getInteger("page", GENE_REQUEST_GET);
			if (!$page OR $page > $numpages) {
				$page = 1;
			}
			
			$this->model->setPageNumber($page);
			$tpl->assign ("pagenum", $page);
			$tpl->assign ("numpages", $numpages);
			
			$tag = preg_replace('/\s\s+/', ' ', preg_replace("/[^a-zA-Z0-9 ]/", "", strtolower(trim($tag))));
			$tpl->assign("showingtag", $tag);
			
			if ($showingusertag) {
				$discussions = $usertagset->getObjectsByLabel($tag, array(
					"where" => "type='discussion'",
					"tables" => array(Gene::tableName("discussions"), Gene::tableName("object_guests")),
					"order" => "priority DESC, last_comment_time DESC",
				));
			} else {
				$discussions = $worldset->getObjectsByLabel($tag, array(
					"where" => "type='discussion'",
					"tables" => array(Gene::tableName("discussions"), Gene::tableName("object_guests")),
					"order" => "priority DESC, last_comment_time DESC",
				));
			}
		} else {
			/* Get All Discussions */
			$numpages = $this->model->getNumPages();
			$page = Gene_Request::getInteger("page", GENE_REQUEST_GET);
			if (!$page OR $page > $numpages) {
				$page = 1;
			}
			
			$this->model->setPageNumber($page);
			$tpl->assign ("pagenum", $page);
			$tpl->assign ("numpages", $numpages);
		
			if (isset($actions[2]) && $actions[2] == "mine" && $user->getUserId()) {
				$user =& Gene::getUser();
				$tpl->assign ("mine", true);
				$discussions = $this->model->getChilds(array(
					"where" => "(type='discussion' OR type='redirect') AND owner_id='".$user->getUserId()."'",
					"tables" => Gene::tableName("discussions"),
					"order" => "priority DESC, last_comment_time DESC",
				));
			} else {
				$discussions = $this->model->getChilds(array(
					"where" => "type='discussion' OR type='redirect'",
					"tables" => array(Gene::tableName("discussions"), Gene::tableName("object_guests")),
					"order" => "priority DESC, last_comment_time DESC",
				));
			}
		}
		
		if (count($discussions)) {
			/* Get read information */
			$user =& Gene::getUser();
			if ($user->getUserId()) {
				$member = $user->getInfo();
				
				foreach ($discussions as $i) {
					$discussionids[] = $i['object_id'];
				}
				
				$read = $db->extended->getAssoc("SELECT discussion_id, comments FROM ".Gene::tableName("discussion_read")." WHERE user_id=? AND discussion_id IN (".implode(",", $discussionids).")", null, array($member['user_id']));
				
				foreach ($discussions as $j => $k) {
					if (isset($read[$k['object_id']])) {
						if ($read[$k['object_id']] <= $k['numchilds']) {
							$discussions[$j]['unread'] = true;
						} else {
							$discussions[$j]['unread'] = false;
						}
					} else {
						$discussions[$j]['unread'] = true;
					}
				}
			}
		}
		
		if (count($forums) OR count($discussions)) {
			/* Get last post object information */
			$lastids = array();
			
			foreach ($discussions as $i) {
				if ($i['last_comment_id']) {
					$lastids[] = $i['last_comment_id'];
				}
			}
			
			foreach ($forums as $i) {
				if ($i['last_comment_id']) {
					$lastids[] = $i['last_comment_id'];
				}
			}
			
			if (count($lastids)) {
				$lastinfo = $db->extended->getAssoc("SELECT g.*, o.*, u.name FROM ".Gene::tableName("objects")." o LEFT JOIN ".Gene::tableName("user_info")." u ON (o.owner_id=u.user_id) LEFT JOIN ".Gene::tableName("object_guests")." g ON (o.object_id=g.object_id) WHERE o.object_id IN (".implode(",", array_unique($lastids)).")");
				
				foreach ($lastinfo as $j => $k) {
					$lastinfo[$j]['object_id'] = $j;
				}
				
				foreach ($discussions as $j => $k) {
					if (isset($lastinfo[$k['last_comment_id']])) {
						$discussions[$j]['lastcomment'] = $lastinfo[$k['last_comment_id']];
					}
				}
			}
			
			$forumread = $db->extended->getAssoc("SELECT forum_id, time FROM ".Gene::tableName("forum_read")." WHERE user_id=? AND parent_id=?", null, array($user->getUserId(), $info['object_id']));
			
			foreach ($forums as $j => $k) {
				if (isset($lastinfo[$k['last_comment_id']])) {
					if (!isset($forumread[$k['object_id']]) OR $lastinfo[$k['last_comment_id']]['t_create'] > $forumread[$k['object_id']]) {
						$forums[$j]['unread'] = true;
					} else {
						$forums[$j]['unread'] = false;
					}
					
					$forums[$j]['lastcomment'] = $lastinfo[$k['last_comment_id']];
				} else {
					$forums[$j]['unread'] = false;
				}
			}
		}
		
		$tpl->assign ("childs", array_merge($forums, $discussions));
		
		// These vars make it a ton easier to do templates
		$pinned = array();
		$normal = array();
		
		foreach ($discussions as $i) {
			if ($i['priority'] > 1) {
				$pinned[] = $i;
			} else {
				$normal[] = $i;
			}
		}
		
		$tpl->assign ("forums", $forums);
		$tpl->assign ("pinned", $pinned);
		$tpl->assign ("normal", $normal);
		
		if (!$standalone && $user->getUserId()) {
			$parent = Gene_Object::get($this->model->getCentreId());
			$tpl->assign ("myforums", $parent->getMyForums());
		}
		
		// Popular Tags
		$populartags = $worldset->getPopularLabels(50);
		$labels = array();
		$objects = array();
		foreach ($populartags as $j => $k) { // Reorder tags alphabetically
			$labels[$j] = $k['label'];
			$objects[$j] = $k['objects'];
		}
		array_multisort($labels, SORT_ASC, $populartags);

		$tpl->assign ("globaltags", $populartags);
		
		if (isset($showingusertag) && $showingusertag) {	
			$tpl->assign ("usertags", $usertagset->getLabels());
		} else {
			$tpl->assign ("usertags", $userset->getLabels());
		}
		
		$tpl->append ("portlets", "forum");
		
		if ($this->model->canModerate()) {
			$tpl->assign ("reports", $this->model->getReports(true));
		}
		
		/* Update Forum Read Status */
		if ($user->getUserId()) {
			$u = $db->extended->autoExecute(
				Gene::tableName("forum_read"),
				array(
					"time" => time()
				),
				MDB2_AUTOQUERY_UPDATE,
				"user_id=".$db->quote($user->getUserId())." AND forum_id=".$db->quote($info['object_id'])
			);
		
			if (!$u) {
				$db->extended->autoExecute(
					Gene::tableName("forum_read"),
					array(
						"user_id" => $user->getUserId(),
						"forum_id" => $info['object_id'],
						"parent_id" => $info['parent'],
						"time" => time(),
					),
					MDB2_AUTOQUERY_INSERT
				);
			}
		}

		return $tpl->fetch("objects/forum/view");
	}
	
	/**
	 * Callback function to specify object specific edit actions.
	 */
	function getCustomEditActions() {
		if ($this->model->canModerate()) {
			$this->editActions['icon'] = "Icon";
			$this->editActions['reports'] = "Reports";
		}
	}
	
	/**
	 * Callback function to call specific edit action
	 */
	function callCustomEditAction($action) {
		$tpl =& Gene::getTemplate();
		$db =& Gene::getDatabase();
		
		$info = $this->model->get();
		
		if ($action == "icon" && $this->model->canModerate()) {
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				if (Gene_Request::getBoolean("remove", GENE_REQUEST_POST)) {
					$db->extended->autoExecute(
						Gene::tableName("forums"),
						array(
							"icon_new" => 0,
							"icon_nonew" => 0
						),
						MDB2_AUTOQUERY_UPDATE,
						"object_id=".$db->quote($info['object_id'])
					);
				}
				else if (isset($_FILES['forumicon'])) {
					if ($_FILES['forumicon']['error'] == 4) {
						$tpl->assign ("errormsg", "You did not upload a forum icon.");
					} else if ($_FILES['forumicon']['error']) {
						$tpl->assign ("errormsg", "An error occured whilst uploading the forum icon.");
					} else {
						if (in_array($_FILES['forumicon']['type'], array("image/jpeg", "image/gif", "image/png"))) {
							require_once ("Gene/File/Common.php");
							$file =& Gene_File_Common::create($_FILES['forumicon']['type']);
							
							if ($content = file_get_contents($_FILES['forumicon']['tmp_name'])) {
								$file->setContent($content);
								if ($file->isSupported()) {
									$file->setSystem(true);
									$file->resizeCrop(100,100);
									$file->updateContentFromResource();
									$file->save();
									
									// Create a gray clone of image
									$inactive =& $file->cloneFile();
									$inactive->setSystem(true);
									$inactive->grayscale();
									$inactive->updateContentFromResource();
									$inactive->save();
									
									$db->extended->autoExecute(
										Gene::tableName("forums"),
										array(
											"icon_new" => $file->getId(),
											"icon_nonew" => $inactive->getId()
										),
										MDB2_AUTOQUERY_UPDATE,
										"object_id=".$db->quote($info['object_id'])
									);
								} else {
									$tpl->assign ("errormsg", "An error occured whilst uploading the forum icon.");
								}
							} else {
								$tpl->assign ("errormsg", "An error occured whilst uploading the forum icon.");
							}
						}
					}
				} else {
					$tpl->assign ("errormsg", "You did not upload a forum icon.");
				}
			}
				
			$q = $db->prepare ("SELECT * FROM ".Gene::tableName("forums")." WHERE object_id=?");
			$res = $q->execute(array($info['object_id']));
			$tpl->assign ("foruminfo", $res->fetchRow());
			$res->free();
			
			return $tpl->fetch ("objects/forum/edit/icon");
		} else if ($action == "reports" && $this->model->canModerate()) {
			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				$objectid = Gene_Request::getInteger("object", GENE_REQUEST_POST);
				if ($object =& Gene_Object::get($objectid) && $object->canModerate()) {
					$report =& $object->getReport();
					$info = $object->get();
					if ($info['type'] == "discussion" OR $info['type'] == "discussioncomment") {
						$report->removeAll();
						$tpl->assign ("removed", true);
					}
				}
			}
			
			$moreinfo = Gene_Request::getInteger("more", GENE_REQUEST_GET);
			if ($moreinfo && $object =& Gene_Object::get($moreinfo) && $object->canModerate()) {
				$report =& $object->getReport();
				$info = $object->get();
				if ($info['type'] == "discussion" OR $info['type'] == "discussioncomment") {
					$tpl->assign ("reportstrings", array(
						"1" => "Abusive",
						"2" => "Offensive or Inappropiate",
						"3" => "Language",
						"4" => "Spam",
						"5" => "Off Topic",
						"6" => "Other",
					));
					
					$tpl->assign ("reportobject", $info);
					$tpl->assign ("objectreports", $report->getAll());
				}
			}
			
			$reports = $this->model->getReports(false, true);
			foreach ($reports as $j => $k) {
				Gene_Object::cacheObject($k['object_id'], $k);
			}
			
			$tpl->assign ("reports", $reports);
			$tpl->append("stylesheets", "discussion");
			return $tpl->fetch ("objects/forum/edit/reports");
		}
	}
	
	/**
	 * Displays the object creation form for this type of object.
	 *
	 * @static
	 *
	 * @return string HTML output for object creation.
	 */
	function create() {
		$tpl =& Gene::getTemplate();
		return $tpl->fetch("objects/forum/create");
	}
}
 
?>